package com.niit.service.impl;

import com.niit.bean.R;
import com.niit.dao.RatingRepository;
import com.niit.entity.Rating;
import com.niit.service.RatingService;
import com.niit.utils.Constant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class RatingServiceImpl implements RatingService {
    @Autowired
    private RedisService redisService;
    @Autowired
    private RatingRepository ratingRepository;

    @Override
    public R addRating(Rating rating) {
        // 判断用户是否已经给商品打分了
        Rating existRating = ratingRepository.findRatingByProductIdAndUserId(rating.getProductId(), rating.getUserId());
        // 时间戳
        Integer timestamp = Long.valueOf(System.currentTimeMillis()/1000).intValue();
        if (existRating == null){
            // 不存在则直接入库（mongodb）
            rating.setTimestamp(timestamp);
            ratingRepository.save(rating);
            //埋点：记录用用户打分行为
            log.info(Constant.PRODUCT_RATING_PREFIX + ":" + rating.getUserId() +"|"+ rating.getProductId() +"|"+ rating.getScore() +"|"+ System.currentTimeMillis()/1000);
            // 更新redis中的数据
            updateRedis(rating);
            return R.ok().message("打分完成！！");
        }
        // 存在则更新
        existRating.setScore(rating.getScore());
        existRating.setTimestamp(timestamp);
        ratingRepository.save(existRating);
        //埋点：记录用用户打分行为
        log.info(Constant.PRODUCT_RATING_PREFIX + ":" + rating.getUserId() +"|"+ rating.getProductId() +"|"+ rating.getScore() +"|"+ System.currentTimeMillis()/1000);
        // 更新redis中的数据
        updateRedis(existRating);
        return R.ok().message("更新打分完成！！");
    }
    private void updateRedis(Rating rating) {
        if (redisService.exists("userId:" + rating.getUserId()) && redisService.llen("userId:" + rating.getUserId()) >= Constant.REDIS_PRODUCT_RATING_QUEUE_SIZE) {
            redisService.rpop("userId:" + rating.getUserId());
        }
        String key = "userId:" + rating.getUserId();
        String value = rating.getProductId() + ":" + rating.getScore();
        redisService.leftPush(key.trim(),value.trim());
    }
}
